package handler

import (
	"fmt"
	"gitee.com/DonHz/simple-blog-system/config"
	"gitee.com/DonHz/simple-blog-system/model"
	"gitee.com/DonHz/simple-blog-system/util/jwtx"
	"gitee.com/DonHz/simple-blog-system/util/logger"
	"gitee.com/DonHz/simple-blog-system/util/stringx"
	"github.com/gin-gonic/gin"
	"time"
)

func (u *UserHandler) Login(ctx *gin.Context) {
	name:=ctx.PostForm("user")
	password:=ctx.PostForm("password")
	if len(name)==0 {
		ReturnError(ctx, 5, "must indicate user name")
		return
	}
	if len(password) !=32 {
		ReturnError(ctx, 5, "invalid password")
		return
	}

	user, err:=u.dao.GetUserByName(ctx, name)
	fmt.Println(user)
	if err!=nil{
		logger.LogRus.Errorf("get user by name failed, error: %v", err)
		ReturnError(ctx, 4, "系统异常")
		return
	}
	if user.Password!=password{
		ReturnError(ctx, 4, "用户名或密码错误")
		return
	}
	logger.LogRus.Infof("user %s Id %d login", name, user.Id)
	// 登录成功后向客户端返回 双token
	header:= jwtx.DefaultHeader
	payload:= jwtx.JWTPayload{
		Issue: "blog",
		IssueAt: time.Now().Unix(),
		Expiration: time.Now().Add(model.TOKEN_EXPIRE).Add(24*time.Hour).Unix(),
		UserDefined: map[string]any{
			"uid": user.Id,
		},
	}
	token, err:= jwtx.GenJWT(header, payload, config.JWT_SECRET)
	if err!=nil{
		logger.LogRus.Errorf("生成token失败：%v", err)
		ReturnError(ctx, 5, "生成token失败")
		return
	}
	refreshToken:= stringx.RandStringRunes(20) //生成长度为20的随机字符作为refresh_token
	err = model.SetToken(refreshToken, token)
	if err!=nil{
		logger.LogRus.Errorf("存储双token到redis失败：%v", err)
		ReturnError(ctx, 5, "系统错误")
		return
	}
	ctx.SetCookie("refresh_token", refreshToken,
		int(model.TOKEN_EXPIRE.Seconds()),
		"/",
		"localhost",
		false,
		true,
	)
	ctx.JSON(200, LoginResponse{
		Uid: user.Id,
		Token: token,
	},)
}

type LoginResponse struct {
	Uid int64 `json:"uid"`
	Token string `json:"token"`
}
